package deployr.core;

import java.util.*;

import deployr.domain.*;

public class Projects implements Iterable<IProject> {

	private final List<IProject> projects = new LinkedList<IProject>();

	private final String commonPath;

	private SaveOn saveOnPlace;

	public Projects() {
		this.commonPath = "";
	}

	public Projects(final String commonPath) {
		this.commonPath = commonPath;
	}

	public void save(IProject project) {
		if(null != saveOnPlace) saveOnPlace.save(project);
	}

	public Projects(final String commonPath, final Iterable<IProject> projects) {
		this.commonPath = commonPath;

		if (projects != null) {
			for (final IProject project : projects) {
				addProject(project);
			}
		}
	}

	private void addProject(final Project project) {
		projects.add(project);
	}
	
	public Project createAndAddProject(AppId appId) {
		return createAndAddProject(appId.getGroupId(), appId.getArtifactId(), appId.getVersion());
	}

	public Project createAndAddProject(final String groupId, final String artifactId, final String version) {
		final Project project = new Project(groupId, artifactId, version);
		addProject(project);
		save(project);
		return project;
	}

	public String commonPath() {
		return commonPath;
	}

	public boolean empty() {
		return projects.isEmpty();
	}

	public Iterator<IProject> iterator() {
		return projects.iterator();
	}

	public IProject select(final String md5) {
		return new Select(projects).firstMatch(md5);
	}

	public Projects matches(final String path) {
		final Projects matchedProjects = new Projects(path);

		for (final IProject project : projects) {
			if (project.pathStartsWith(path)) {
				matchedProjects.addProject(project);
			}
		}

		return matchedProjects;
	}

	@Override
	public String toString() {
		return projects.toString();
	}

	public Iterable<IProject> getProjects() {
		return projects;
	}

	public void addProject(IProject project) {
		projects.add(project);
	}

	public void eraseChecksum(IProject project) {
		project.updateChecksum("");
	}

	public void saveOn(SaveOn saveOnPlace) {
		this.saveOnPlace = saveOnPlace;		
	}

	public int size() {
		return projects.size();
	}
}